$(function () {

    var gameField = "                                              ";
    var clicks = 0;
    var firstClickID;
    var secondClickID;
    var playerLetter = "a";
	var playerId = null;
    var games=null;
	var nextPlayer ="a";
	var selectedGameId =null;
    var gameState = null;
	
	var baseUrl = 'http://' +document.location.host;
	
	var updated = true;
	
    function GetCoordinates(event) {
		if(selectedGameId!==null)
		{
			if(playerLetter === nextPlayer && selectedGameId!==null)
			{
			
				clicks++;
				if (clicks == 1) {
					firstClickID = event.target.id;
					var element = $('#' + firstClickID);
					element.css('opacity', '0.2');
				}
				else if (clicks == 2) {
					secondClickID = event.target.id;
					CheckIfMoveValid();
					var element = $('#' + firstClickID);
					element.css('opacity', '1');
					clicks = 0;
				}
			}
			else
			{
				alert("Other player turn.");
			}
		}
		else
		{
			alert("Join a game first.Click on the game name to join.");
		}
    }
    function CheckIfMoveValid() {
        var enemyLetter = "a";
        if (playerLetter === "a") {
            enemyLetter = "b";
        }
        var xValid = (parseInt(firstClickID / 10) == parseInt(secondClickID / 10)) || (Math.abs(parseInt(firstClickID / 10) - parseInt(secondClickID / 10)) == 2);
        var yValid = (firstClickID % 10 == secondClickID % 10) || (Math.abs(firstClickID % 10 - secondClickID % 10) == 2);
        if (xValid && yValid && firstClickID != secondClickID) {
            var firstCellValid = gameField[firstClickID].toLowerCase() != enemyLetter;
            var middleCellID = (10 * (parseInt(firstClickID / 10) + parseInt(secondClickID / 10)) / 2) + (((firstClickID % 10) + (secondClickID % 10)) / 2);
            var secondCellValid = gameField[middleCellID].toLowerCase() != enemyLetter;
            var thirdCellValid = gameField[secondClickID].toLowerCase() != enemyLetter;
            if (firstCellValid && secondCellValid && thirdCellValid) {
                if (gameField[firstClickID] == ' ' || gameField[middleCellID] == ' ' || gameField[secondClickID] == ' ') {
                    ChangeCells(middleCellID);
                }
            }
        }
    }
    function ChangeCells(middleCellID) {
        var x1 = parseInt(firstClickID / 10);
		var x2 = parseInt(secondClickID / 10);
		var y1 = firstClickID % 10;
		var y2 = secondClickID % 10;
		 
		 var mover ={
        StartX:x1,
        StartY:y1,
        EndX:x2,
        EndY:y2,
        PlayerSymbol:playerLetter,
        GameID:games[selectedGameId].Id,
		};
		var moveUrl = baseUrl+"/TrippleGameService.svc/Move";
        $.ajax({
            type: "POST",
            async: true,
            url: moveUrl,
            data: JSON.stringify(mover),
            contentType: "application/json; charset=utf-8",
            success: function (result) {
               if(result == "Invalid move")
			   {
				alert("Invalid move");
			   }
			   else
			   {
				gameField= result;
				games[selectedGameId].Matrix = result;
				RefreshBoard();
				getNextPlayer();
			   }
			   
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    }
	
	function update()
	{
		if(selectedGameId !== null && updated === true && games[selectedGameId].Id !== undefined)
		{
		updated = false;
			var nextPlayerUrl = baseUrl+"/TrippleGameService.svc/Update";
			$.ajax({
				type: "POST",
				async: true,
				url: nextPlayerUrl,
				data: JSON.stringify(games[selectedGameId].Id),
				contentType: "application/json; charset=utf-8",
				success: function (result) {
					nextPlayer = result.NextPlayerSymbol;
                    gameField = result.Matrix;
					RefreshBoard();
					if((result.GameState === "Winner:A" || result.GameState === "Winner:B" ||
					result.GameState === "Draw") && gameState !== result.GameState)
					{
						alert(result.GameState);
					}
					gameState = result.GameState;
					updated = true;
					
				},
				error: function (xhr, ajaxOptions, thrownError) {
					alert(xhr.status);
					alert(thrownError);
				}
			});
		}
	}
	
	setInterval(function()
		{
			update();
		}	, 500);
	
	function getNextPlayer() {
	
		var jData = {  PlayerLetter: playerLetter, Matrix:gameField, GameId:games[selectedGameId].Id};
		var nextPlayerUrl = baseUrl+"/TrippleGameService.svc/GetNextPlayer";
        $.ajax({
            type: "POST",
            async: true,
            url: nextPlayerUrl,
            data: JSON.stringify(jData),
            contentType: "application/json; charset=utf-8",
            success: function (result) {
				nextPlayer = result;
			   
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
	}
	
	function joinGame() {
	
		var jData = { GameId:games[selectedGameId].Id, PlayerId:playerId};
		var nextPlayerUrl = baseUrl+"/TrippleGameService.svc/JoinGame";
        $.ajax({
            type: "POST",
            async: true,
            url: nextPlayerUrl,
            data: JSON.stringify(jData),
            contentType: "application/json; charset=utf-8",
            success: function (result) {
				playerLetter=result;
				var x = games[selectedGameId].Name;
				$('#currentGame').text("Joined game:" +x.toString());
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
		}
	
	
	$('#createPlayer').click(function() {
	
		var gameName = $('#playerNameField').val();
		
		var nextPlayerUrl = baseUrl+"/TrippleGameService.svc/CreatePlayer";
        $.ajax({
            type: "POST",
            async: true,
            url: nextPlayerUrl,
            data: JSON.stringify(gameName),
            contentType: "application/json; charset=utf-8",
            success: function (result) {
				alert('Player created!');
				playerId = result;
				$('#playerNameField').attr("disabled", "disabled");
				$('#createPlayer').attr("disabled", "disabled");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
	})
	
    function CreateBoard() {
        var board = document.getElementById("gameboard");
        for (var i = 0; i < 5; i++) {
            var rows = $('table tr');
            var row = rows[i];
            for (var j = 0; j < 10; j++) {
                var cell = $("<td class='cell'></td>");
                cell.click(function () { GetCoordinates(event) });
                cell.appendTo(row);
                var coordinate = i * 10 + j;
                var image = $("<img width=100% src='images/EmptyCell.png' id=" + coordinate + " />");
                image.appendTo(cell);
            }
        }
        RefreshBoard();
		loadAvailableGames();
    }
	
	$('#createGameButton').click(function createNewGame() {
	
		var gameName = $('#createGameField').val();
		
		var nextPlayerUrl = baseUrl+"/TrippleGameService.svc/CreateNewGame";
        $.ajax({
            type: "POST",
            async: true,
            url: nextPlayerUrl,
            data: JSON.stringify(gameName),
            contentType: "application/json; charset=utf-8",
            success: function (result) {
				alert('Game created');
				loadAvailableGames();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
	
	});

    function RefreshBoard() {
        var images = $('table tr td img');
        for (var i = 0; i < 50; i++) {
            switch (gameField[i]) {
                case ' ':
                    images[i].src = "images/EmptyCell.png";
                    break;
                case 'A':
                    images[i].src = "images/1stPlayerLastMove.png";
                    break;
                case 'a':
                    images[i].src = "images/1stPlayer.png";
                    break;
                case 'B':
                    images[i].src = "images/2ndPlayerLastMove.png";
                    break;
                case 'b':
                    images[i].src = "images/2ndPlayer.png";
                    break;
                default:
                    break;
            }
        }

    }
	
	$('#refreshGames').click(loadAvailableGames);
	
	function loadAvailableGames() {
        var showGamesUrl = baseUrl+"/TrippleGameService.svc/ShowAvailableGames";
        $.ajax({
            type: "GET",
            async: true,
            url: showGamesUrl,
            data: null,
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                games = result;
				$('.game').remove();
                for (var i = 0; i < result.length; i++) {
                    $('#availableGames').append('<div class="game" id=Game' + i + '>' + result[i].Name +' : '+result[i].State+'</div>');
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
        return false;
    }


    $('body').ready(CreateBoard)
	
	   $('.game').live("click",
		function selectGame() {
		    if(playerId === null)
		{
			alert("You must first create a player!");
		}
		else
		{
			var selectedGame = $(this).attr("id");
			var oldSelected = selectedGameId;
			selectedGameId = selectedGame.substring(4);
            if(games[selectedGameId].State ==="STARTED")
            {
                alert("The game you are trying to join is already full!");
				selectedGameId = oldSelected;
            }
            else
            {
			gameField = games[selectedGameId].Matrix;
			RefreshBoard();
			joinGame();
			loadAvailableGames();
            }
		}
		});
});
